package com.colin.util.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 分页执行工具类
 *
 * @author zhaolz
 * @date 2022/1/26 19:31
 */
public class PageRunUtil {

    public static <T> void toRun(List<T> list, Integer pageSize, PageRunFunction<T> function) {
        if (list == null || list.size() < 1) {
            return;
        }
        if (list.size() < pageSize) {
            function.run(list);
            return;
        }
        int total = list.size();
        int page = total / pageSize + 1;
        for (int i = 0; i < page; i++) {
            int start = i * pageSize;
            int end = Math.min((start + pageSize), total);
            List<T> longs = list.subList(start, end);
            if (CollectionUtils.isNotEmpty(longs)) {
                function.run(longs);
            }
        }
    }

    public static <T, V> List<V> toRunWithReturn(List<T> list, Integer pageSize, PageRunWithReturnFunction<T, V> function) {
        if (list == null || list.size() < 1) {
            return null;
        }
        if (list.size() < pageSize) {
            return function.run(list);
        }
        List<V> result = new ArrayList<>(list.size());
        int total = list.size();
        int page = total / pageSize + 1;
        for (int i = 0; i < page; i++) {
            int start = i * pageSize;
            int end = Math.min((start + pageSize), total);
            List<T> longs = list.subList(start, end);
            if (CollectionUtils.isNotEmpty(longs)) {
                result.addAll(function.run(longs));
            }
        }
        return result;
    }

    @FunctionalInterface
    public interface PageRunFunction<T> {
        void run(List<T> list);
    }

    @FunctionalInterface
    public interface PageRunWithReturnFunction<T, V> {
        List<V> run(List<T> list);
    }

    public static void main(String[] args) {
        List<Integer> aa = new ArrayList<>();
        aa.add(1);
        aa.add(2);
        aa.add(3);
        aa.add(4);
        aa.add(5);
        aa.add(6);
        aa.add(7);
        toRun(aa, 3, new PageRunFunction<Integer>() {
            @Override
            public void run(List<Integer> list) {
                System.out.println(JSONObject.toJSONString(list));
            }
        });

        List<String> list = toRunWithReturn(aa, 3, new PageRunWithReturnFunction<Integer, String>() {
            @Override
            public List<String> run(List<Integer> list) {
                List<String> result = new ArrayList<>(list.size());
                for (Integer i : list) {
                    result.add(i + "_result");
                }
                return result;
            }
        });
        System.out.println(JSONObject.toJSONString(list));

    }

}
